package com.atguigu.srb.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.base.exception.SrbException;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResultCodeEnum;
import com.atguigu.srb.entity.Dict;
import com.atguigu.srb.entity.IntegralGrade;
import com.atguigu.srb.entity.excel.DictExcelVo;
import com.atguigu.srb.listener.DictExcelListener;
import com.atguigu.srb.service.DictService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/admin/dict")
public class AdminDictController {
    @Autowired
    DictService dictService;
    //返回值类型：统一响应类 Result (code message data)
    @GetMapping("list")
    public R<List<Dict>> list(){
        return R.ok(dictService.list());
    }
    //根据id查询
    @GetMapping("{id}")
    public R<Dict> getById(@PathVariable("id")Long id){

        return R.ok(dictService.getById(id));
    }
    //删除
    @DeleteMapping("{id}")
    public R<Boolean> deleteById(@PathVariable("id")Long id){

        return R.ok(dictService.removeById(id));
    }
    //更新: 要更新的数据通过请求体提交(提交的对象数据包含id)
    @PutMapping
    public R<Boolean> updateById(@RequestBody Dict dict){
        if(dict.getId()==null){
//            throw new RuntimeException()
            //业务判断失败，可以失败的原因显示告诉用户
            throw new SrbException(ResultCodeEnum.UPDATE_DATA_ERROR);
        }
        return R.ok(dictService.updateById(dict));
    }
    //新增：  数据没有id
    @PostMapping
    public R<Boolean> save(@RequestBody Dict dict){

        return R.ok(dictService.save(dict));
    }
    // 导出数据
    @GetMapping("export")
    public void  exportDicts(HttpServletResponse response){ //response可以自定义响应报文
        dictService.exportDicts(response);

    }
    @Autowired
    DictExcelListener dictExcelListener;
    //导入数据
    @PostMapping("import")
    @SneakyThrows
    public R  importDicts(MultipartFile file){ //response可以自定义响应报文
//        dictService.exportDicts(response);
        EasyExcel.read(file.getInputStream()) //基于本地文件解析
                .sheet(0) //表示要读取excel文件的哪个工作簿(  0表示第一个)
                .head(DictExcelVo.class) //必须指定 和excel文件映射的实体类 来解析
                .registerReadListener(dictExcelListener) //配置回调监听器(编写了处理解析得到的数据的业务)
                .doRead(); //执行解析

        return R.ok().message("导入成功");
    }
}
